package org.lex.swing.util;

import java.awt.FlowLayout;

import javax.swing.Action;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.border.Border;
import javax.swing.border.EmptyBorder;

public class Buttons extends JPanel {
	private static final Border BORDER = new EmptyBorder(12, 1, 11, 0);

	/***************************************************************************
	 * Create a panel, buttons will be put in the trailing edge of the panel's
	 * orientation,
	 **************************************************************************/
	public static Buttons trailing(String... texts) {
		return new Buttons(FlowLayout.TRAILING, createButtons(texts));
	}

	public static <T extends Action> Buttons trailing(T... actions) {
		return new Buttons(FlowLayout.TRAILING, createButtons(actions));
	}

	public static Buttons trailing(JButton... buttons) {
		return new Buttons(FlowLayout.TRAILING, buttons);
	}

	/***************************************************************************
	 * Create a panel, buttons will be centered in the panel
	 **************************************************************************/
	public static Buttons center(String... texts) {
		return new Buttons(FlowLayout.CENTER, createButtons(texts));
	}

	public static <T extends Action> Buttons center(T... actions) {
		return new Buttons(FlowLayout.CENTER, createButtons(actions));
	}

	public static Buttons center(JButton... buttons) {
		return new Buttons(FlowLayout.CENTER, buttons);
	}

	static JButton[] createButtons(String... texts) {
		JButton[] buttons = new JButton[texts.length];
		for (int i = 0, n = texts.length; i < n; i++)
			buttons[i] = new JButton(texts[i]);
		return buttons;
	}

	static <T extends Action> JButton[] createButtons(T... actions) {
		JButton[] buttons = new JButton[actions.length];
		for (int i = 0, n = actions.length; i < n; i++)
			buttons[i] = new JButton(actions[i]);
		return buttons;
	}

	private JButton[] buttons = null;

	public Buttons(int align, JButton... buttons) {
		super(new FlowLayout(align, 11, 0));
		this.setBorder(BORDER);
		this.setButtons(buttons);
	}

	public JButton getButton(int index) {
		return this.buttons[index];
	}

	private void setButtons(JButton... buttons) {
		this.buttons = new JButton[buttons.length];
		for (int i = 0, n = buttons.length; i < n; i++) {
			JButton b = buttons[i];
			this.buttons[i] = b;
			if (null != b)
				super.add(b, null);
		}
	}
}
